package com.example.mqtt.config;

import org.eclipse.paho.client.mqttv3.IMqttClient;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MqttConfig {
    @Value("${mqtt.broker}")
    private String broker;

    @Value("${mqtt.producer.client-id}")
    private String producerClientId;

    @Value("${mqtt.consumer.client-id}")
    private String consumerClientId;

    @Bean("mqttProducer")
    public IMqttClient mqttProducer() throws MqttException {
        IMqttClient producer = new MqttClient(broker, producerClientId);
        producer.connect(mqttConnectOptions());
        return producer;
    }

    @Bean("mqttConsumer")
    public IMqttClient mqttConsumer() throws MqttException {
        IMqttClient consumer = new MqttClient(broker, consumerClientId);
        consumer.connect(mqttConnectOptions());
        return consumer;
    }

    private MqttConnectOptions mqttConnectOptions() {
        MqttConnectOptions options = new MqttConnectOptions();
        options.setAutomaticReconnect(true);
        options.setCleanSession(true);
        return options;
    }
}